package com.shenxuchen.crm.web.controller;

import com.shenxuchen.crm.pojo.Type;
import com.shenxuchen.crm.service.TypeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("type")
public class TypeController {
    @Resource
    private TypeService typeService;


    @PostMapping("edit")
    public String edit(Type type) {
        typeService.edit(type);
        return "redirect:index.html";
    }

    @GetMapping("delete")
    public String delete(String[] codes) {
        typeService.delete(codes);
        return "redirect:index.html";
    }

    @GetMapping("edit.html")
    public ModelAndView edit(String code) {
        Type type = typeService.getByCode(code);
        ModelAndView mv = new ModelAndView();
        // 添加数据到request作用域
        mv.addObject("type", type);
        // 设置视图的名字
        mv.setViewName("dictionary/type/edit");
        return mv;
    }

    @GetMapping("exists")
    @ResponseBody
    public Boolean exists(String code) {
        return typeService.getExists(code);
    }

    @PostMapping("save")
    public String save(Type type) {
        typeService.save(type);
        return "redirect:index.html";
    }

    @GetMapping("index.html")
    public ModelAndView index() {
        List<Type> typeList = typeService.getAll();
        ModelAndView mv = new ModelAndView();
        // 添加数据到request作用域
        mv.addObject("typeList", typeList);
        // 设置视图的名字
        mv.setViewName("dictionary/type/index");
        return mv;
    }
}
